import React from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { routes, RouteType } from './routes'


// 路由拦截 HOC
const BeforeEach = (props) => {
	const { v } = props
	const token = localStorage.getItem('token');

	// 没有token 进入的不是登录页面
	if (!token && v.path !== '/login') {
		// 去登录
		return <Navigate to="/login"></Navigate>
	}

	// 已经登录 跳转的是登录
	if (token && v.path === '/login') {
		// 去首页
		return <Navigate to="/"></Navigate>
	}

	return <v.element></v.element>
}

// 路由的递归渲染
const routerView = (routes: RouteType) => {
	return routes.map((v, i) => {
		return <Route path={v.path} element={<BeforeEach v={v}></BeforeEach>} key={i}>
			{v.children && routerView(v.children)}
		</Route>
	})
}


const Router: React.FC = () => {
	return (
		<BrowserRouter>
			<Routes>
				{
					routerView(routes)
				}
			</Routes>
		</BrowserRouter>
	)
}

export default Router